﻿#region 命名空间

using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq;
using WinnerCMS.Common;
using WinnerCMS.Data;
using WinnerCMS.Model;
using WinnerCMS.Common.Security;
using WinnerCMS.PlugIn.OpenAPI;
using WinnerCMS.PlugIn.OpenAPI.Passport;

#endregion

namespace WinnerCMS.BLL
{
    /// <summary>
    /// 前台专用
    /// </summary>
    public class Public_Member : IMember
    {
        private static readonly UserDal Dal = new UserDal();

        /// <summary>
        /// 外部调用
        /// </summary>
        public bool IsOutSidePost = true;

        /// <summary>
        /// 专门給外部API接口调用的，如果是外部调用，不会访问外网接口
        /// </summary>
        public Public_Member()
        {
        }

        /// <summary>
        /// 专门給本站用的，实例化的时候用这个构造函数将会引发访问外网的接口
        /// </summary>
        /// <param name="isApiPost"></param>
        public Public_Member(bool isApiPost)
        {
            this.IsOutSidePost = false;
        }

        #region 注册会员和修改会员

        /// <summary>
        /// 注册会员和修改会员
        /// </summary>
        public void RegMember(User model, string passCode, ref string strErr)
        {
            if (model.UserName.Length == 0)
            {
                strErr = "用户名不能为空。";
                return;
            }
            if (string.IsNullOrEmpty(model.PetName))
            {
                model.PetName = model.UserName;
            }
            if (MyValidate.IsEmail(model.EMail) == false)
            {
                strErr = "电子邮件格式错误。";
                return;
            }
            if (passCode != null & passCode.Length == 0) //null 为API里面填写的。
            {
                strErr = "验证码不能为空。";
                return;
            }
            if (HttpContext.Current.Session["VNum"] == null)
            {
                strErr = "验证码过期，请点击验证码更换它。";
                return;
            }
            if (passCode != HttpContext.Current.Session["VNum"].ToString())
            {
                strErr = "验证码错误。";
                return;
            }

            if (string.IsNullOrEmpty(model.PetName) == false)
            {
                model.PetName = model.UserName;
            }


            CMSConfig config = CMSConfig.Instance();

            model.Point = config.Member.Point;
            model.Coin = config.Member.Coin;


            if (model.Id == 0)
            {
                Dal.Add(model);

                model.LastLoginIP = HttpClient.GetIP();
                ;
                model = Dal.GetInfo(model.UserName);
                if (model != null)
                {
                    try
                    {
                        if (config.EMail.IsSend)
                        {
                            EMail mail = new EMail();

                            mail.Send("恭喜您，您在《" + WebConfig.SiteName + "》成功注册成为会员",
                                "恭喜您，您在《" + WebConfig.SiteName + "》成功注册成为会员<br>您的用户名为：" + model.UserName, model.EMail,
                                config.EMail.From, config.EMail.FromName, config.EMail.Domain, config.EMail.UserName,
                                config.EMail.PassWord);
                        }
                    }
                    catch
                    {
                        //strErr = "发送注册邮件失败，但已经注册成功！";
                    }
                    //LoginSaveCookie(model);
                }
            }
            else
            {
                Dal.Edit(model);
            }
        }

        #endregion

        #region 修改会员资料--会员自己修改

        public void EditByMemberSelf(MemberInfo model, ref string strErr)
        {
            #region  整合

            if (this.IsOutSidePost == false)
            {
                Client req = new Client(HttpContext.Current);

                model.LastLoginIP = HttpClient.GetIP();

                req.ConnectionAPIs("update", model);

                if (req.ErrList.Count > 0)
                {
                    strErr = "同步修改失败!" + string.Join(",", req.ErrList.ToArray());
                }
            }

            #endregion
        }

        /// <summary>
        /// 修改会员资料--会员自己修改
        /// </summary>
        public void EditByMemberSelf(User user, ref string strErr)
        {
            if (string.IsNullOrEmpty(user.PetName))
            {
                user.PetName = user.UserName;
            }
            if (MyValidate.IsEmail(user.EMail) == false)
            {
                strErr = "电子邮件格式错误。";
                return;
            }
            MemberInfo apiMember = new MemberInfo();
            ModelHelper.CopyValue(user, apiMember);
            EditByMemberSelf(apiMember, ref strErr);

            if (string.IsNullOrEmpty(strErr) == false)
            {
                return;
            }
            Dal.Edit(user);
        }

        #endregion

        #region 后台添加修改会员

        public void RegMember(MemberInfo model, ref string strErr)
        {
            #region 整合

            if (this.IsOutSidePost == false)
            {
                model.Savecookie = "1";
                Client req = new Client(HttpContext.Current);

                if (model.Id == 0)
                {
                    #region 整合

                    req.ConnectionAPIs("reguser", model);

                    if (req.ErrList.Count > 0)
                    {
                        strErr = "同步注册失败!<br/>" + string.Join(",", req.ErrList.ToArray());
                    }

                    #endregion
                }
                else
                {
                    #region 整合

                    req.ConnectionAPIs("update", model);

                    if (req.ErrList.Count > 0)
                    {
                        strErr = "同步修改失败!<br/>" + string.Join(",", req.ErrList.ToArray());
                    }

                    #endregion
                }
            }

            #endregion
        }

        /// <summary>
        /// 后台添加修改会员
        /// </summary>
        /// <param name="model"></param>
        /// <param name="strErr"></param>
        public void Add(User model, ref string strErr)
        {
            if (model.UserName.Length == 0)
            {
                strErr = "用户名不能为空。";
                return;
            }

            if (MyValidate.IsEmail(model.EMail) == false)
            {
                strErr = "电子邮件格式错误。";
                return;
            }

            MemberInfo apiMember = new MemberInfo();
            ModelHelper.CopyValue(model, apiMember);

            RegMember(apiMember, ref strErr);
            if (string.IsNullOrEmpty(strErr) == false)
            {
                return;
            }

            if (model.Id == 0)
            {
                Dal.Add(model);
            }
            else
            {
                Dal.Edit(model);
            }
        }

        #endregion

        #region 删除会员

        /// <summary>
        /// 删除会员
        /// </summary>
        public void Delete(string userName, ref string strErr)
        {
            #region 整合

            if (this.IsOutSidePost == false)
            {
                Client req = new Client(HttpContext.Current);

                MemberInfo model = new MemberInfo();
                model.UserName = userName;

                req.ConnectionAPIs("delete", model);

                if (req.ErrList.Count > 0)
                {
                    strErr = "同步删除失败!<br/>" + string.Join(",", req.ErrList.ToArray());
                    return;
                }
            }

            #endregion

            int memberId = Dal.GetUserId(userName);

            Dal.Delete(memberId);
        }

        #endregion

        #region 登录系统

        public bool AutoLogin { get; set; }

        public bool TryLogin(MemberInfo model, ref string strErr)
        {
            #region  整合

            if (this.IsOutSidePost == false)
            {
                model.Savecookie = "1";
                Client req = new Client(HttpContext.Current);
                req.ConnectionAPIs("login", model);

                if (req.ErrList.Count > 0)
                {
                    strErr = "同步登录失败!\r\n" + string.Join(",", req.ErrList.ToArray());
                    HttpContext.Current.Response.Write(strErr); //登录失败
                    return false;
                }
            }

            #endregion

            return true;
        }

        /// <summary>
        /// 登录系统
        /// </summary>
        /// <param name="model"></param>
        public bool TryLogin(User model, ref string strErr)
        {
            model.LastLoginIP = HttpClient.GetIP();

            MemberInfo apiMember = new MemberInfo();
            ModelHelper.CopyValue(model, apiMember);
            TryLogin(apiMember, ref strErr);
            if (string.IsNullOrEmpty(strErr) == false)
            {
                return false;
            }

            User user = Dal.GetInfo(model.UserName, true);
            if (user == null)
            {
                strErr = "用户不存在"; //登录失败
                return false;
            }
            if (AutoLogin == false)
            {
                model.PassWord = Hash.Md5(model.PassWord);
            }
            if (model.PassWord.Equals(user.PassWord, StringComparison.CurrentCultureIgnoreCase) == false)
            {
                HttpContext.Current.Session.Remove("User");
                strErr = ("登录失败，密码错误"); //登录失败
                return false;
            }
            FormsAuthentication.SetAuthCookie(model.UserName, false);

            return true;
        }

        #endregion

        #region 退出登录

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="username">用户名</param>
        public void MemberLogout(string username)
        {
            FormsAuthentication.SignOut();
            HttpContext.Current.Session.Remove("User");

            HttpCookie myCookie = new HttpCookie("WinnerCMS.com")
            {
                HttpOnly = true
            };
            myCookie.Values.Add("UserName", "过期");
            myCookie.Expires = DateTime.Now.AddDays(-365);

            HttpContext.Current.Response.Cookies.Add(myCookie);

            #region 整合

            if (this.IsOutSidePost == false)
            {
                Client req = new Client(HttpContext.Current);

                MemberInfo model = new MemberInfo
                {
                    UserName = username
                };

                req.ConnectionAPIs("logout", model);
            }

            #endregion
        }

        #endregion

        #region 修改密码

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <param name="PSW1"></param>
        /// <param name="PSW2"></param>
        /// <param name="UpdatePanel1"></param>
        /// <remarks>非接口</remarks>
        public void PasswordModify(string name, string OldPSW, string PSW1, string PSW2, ref string strErr)
        {
            if (PSW2 != PSW1)
            {
                strErr = "两次输入的密码不一致。";
                return;
            }


            //检查旧密码，修改密码一体
            User user = Dal.GetInfo(name);

            if (user.PassWord.Equals(Hash.Md5(OldPSW)))
            {
                //确认密码能够被修改以后，通知远程进行修改密码
                PasswordModify(name, PSW1, ref strErr);
            }
            else
            {
                strErr = "旧密码错误。";
            }
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="name">用户名</param>
        /// <param name="psw">密码</param>
        /// <remarks>实现接口</remarks>
        public void PasswordModify(string name, string psw, ref string strErr)
        {
            MemberInfo model = new MemberInfo();

            #region 整合

            if (this.IsOutSidePost == false)
            {
                Client req = new Client(HttpContext.Current);

                model.UserName = name;
                model.PassWord = psw; //传递明码

                req.ConnectionAPIs("PasswordModify", model);

                if (req.ErrList.Count > 0)
                {
                    strErr = "同步修改密码失败!<br/>" + string.Join(",", req.ErrList.ToArray());
                    return;
                }
            }

            #endregion

            Dal.PasswordModify(name, Hash.Md5(psw));

            //model = dal.GetInfo(Name);
            //if (model != null)
            //{
            //    LoginSaveCookie(model);
            //}
        }

        #endregion

        /// <summary>
        /// 禁止或者开放某个会员
        /// </summary>
        /// <param name="ID"></param>
        public void LockingOrUnLocking(string userName, ref string strErr)
        {
        }
    }
}